import axios,{AxiosError,AxiosRequestConfig,AxiosResponse, InternalAxiosRequestConfig}  from "@ohos/axios"
import {logger} from "./Logger"
import {auth} from "./auth"
import { promptAction, router } from "@kit.ArkUI"
import info from '../model/User'
 export const baseURL="http://123.56.141.187:4001/"
//  export const baseURL="https://huangjiangjun.top:3002/api/mobile_officing/"

export const instance=axios.create({
  baseURL,
  timeout:10000
})
instance.interceptors.request.use((config:InternalAxiosRequestConfig)=>{
  const user=auth.getUser()
  console.log("AppStorage",JSON.stringify(AppStorage))

  console.log(JSON.stringify(user))
  if(user.token){
    config.headers.token=user.token

  }
  return config
},(err:AxiosError)=>{

  console.log(JSON.stringify(err),"err")
  console.log(JSON.stringify(err.response),"err")
  // if(err.response?.status=='400'){
  //   router.pushUrl({
  //     url:"pages/Login"
  //   },router.RouterMode.Single)
  //   promptAction.showToast({message:"登录失效"})
  // }
  return Promise.reject(err)
})
instance.interceptors.response.use((res:AxiosResponse)=>{

  if(res.data.state == '200'||res.data.state == '201'){
    logger.debug("请求成功",JSON.stringify(res.data.data))
    return res.data
  }
  if(res.data.msg == 'TOKEN有误.'){
    console.log("1233")
    router.pushUrl({
      url: 'pages/Login'
    }, router.RouterMode.Single)
    promptAction.showToast({message:"登录失效"})
  }

  logger.error("Error",JSON.stringify(res.data))

  return Promise.reject(res.data)

},(err:AxiosError)=>{
  logger.error("reqerror",JSON.stringify(err))
  return Promise.reject(err)
})
class Http{
  // request<ResponseData, RequestData = Object>(config: AxiosRequestConfig<RequestData>) {
  //   return instance<null, ResponseData, RequestData>(config)
  // }
  request<ResponseData,RequestData=object>(config:AxiosRequestConfig<RequestData>){
    return instance<null,ResponseData,RequestData>(config)
  }
}
export const http=new Http()